#include "common.h"


//本地通信socket，发送建立好的，和用户通信的连接的文件描述符
int local_send(int local_socket, int net_fd){
    
    struct msghdr msg;
    memset(&msg, 0, sizeof(msg));

    //添加正文信息
    char *str = "父子进程传递连接";
    struct iovec iov[1];
    iov[0].iov_base = str;
    iov[0].iov_len = strlen(str);
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    //控制信息
    struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;

    //让p指向cms中，消息头部分
    void *p = CMSG_DATA(cms);
    //转化为int *,因为我们要传递的消息是一个连接，即文件描述符
    int *fd = (int *)p;
    //传递该文件描述符
    *fd = net_fd;

    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    sendmsg(local_socket, &msg, 0);

    return 0;

}


//本地通信socket，用于接受消息的函数，主要是接收主进程发过来的，建立好的连接的文件描述符
int local_recv(int local_socket, int *net_fd){
    
    struct msghdr msg;
    memset(&msg, 0, sizeof(msg));

    //解析正文信息
    char buf[50] = {0};
    struct iovec iov[1];
    iov[0].iov_base = buf;
    iov[0].iov_len = sizeof(buf);
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    //控制信息
    struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;
    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));


    recvmsg(local_socket, &msg, 0);
    
    //让p指向消息头部分
    void *p = CMSG_DATA(cms);
    int *fd = (int *)p;

    *net_fd = *fd;

    return 0;


}
